<?php
require_once (dirname(__FILE__) . "/../config/config.php");

    
    /*
     * 获取活动步骤
     */
    if ($_REQUEST['method'] == "getStep") {
    	
       $result = getStep();
    }
    if ($_REQUEST['method'] == "getField") {
       
        $result = getField();
    }
    if($_REQUEST['method']=="checkEmail")
    {
    	$result=checkEmail();
    }
     if($_REQUEST['method']=="checkMobile")
    {
    	$result=checkMobile();
    }
     if($_REQUEST['method']=="addCustomer")
    {
    	
    	$result=addCustomer();
    }
    
function getStep ()
{
$step=1;
$event_id=null;


if(isset($_REQUEST['event_id']))
{
    $event_id = $_REQUEST['event_id'];
}
if(empty($event_id))
{
    $event_user_id=$_REQUEST['event_user_id'];
    $sqlselect="select * from zy_event_customer where customer_id=".$event_user_id;
	$res = mysql_query($sqlselect);
	$resrow = mysql_fetch_array($res);
	$step=(int)$resrow['step']+1;
    $event_id=$resrow['event_id'];
    $emailaddress=$resrow['emailaddress'];
    $firstname=$resrow['firstname'];
     
}
  /*
   * 获取活动基本信息
   */
    $sql = "select * from zy_event where event_id=".$event_id;
    $rs = mysql_query($sql);
    $row = mysql_fetch_array($rs);
    
    /*
     * 获取指定步骤的内容
     */
    $sqlstep = "select * from zy_event_step where event_id='" . $row[0] . "' and step='".$step."'";
    $rsstep = mysql_query($sqlstep);
    $rowstep = mysql_fetch_array($rsstep);
 /*
  * 获取活动总步数
  */
    $sqlcount = "select * from zy_event_step where event_id='" . $row[0] . "'";
    $count = mysql_num_rows(mysql_query($sqlcount));
    $arr=array();
        $result=array(
            "event_id"=>$row['event_id'],
        	"event_field"=>$rowstep['event_field'],
            "start"=>$row['start_time'],
            "end"=>$row['end_time'],
            "event_user_id"=>$event_user_id,
            'event_banael'=>$row['event_banael'],
            'emailaddress'=>$emailaddress,
            'firstname'=>$firstname,
            'event_code'=>$row['event_code'],
            'partner_id'=>$row['user_id'],
            'allstep'=>$count,
            'step'=>$step,
           	'title'=>$row['event_title'],
            
            
        );
       
       array_push($arr,$result);
    echo json_encode($arr);
   

}
function getField()
{ 
	//$field=unserialize($_POST['field']);
	$field=$_POST['field'];
	$fieldstr=str_replace("\\","",$field);
	$field_value=(unserialize($fieldstr));

	
	$arr=array();
	for ($r = 0; $r < count($field_value); $r ++) {
      
	    $sqlfield = "select * from zy_event_field where field_id=". $field_value[$r]['filed_id'];
	   // echo $sqlfield;
	    $rsfield = mysql_query($sqlfield);
	    while($rowfield = mysql_fetch_array($rsfield)){
	    
	    $result=array(
	    	//"field_id"=>$field[$r]['filed_id'],
 	        "field_name"=>$rowfield['field_name'],
 	        "field_type"=>$rowfield['field_type'],
 	        "event_id"=>$rowfield['event_id'],
 	        "field_label_cn"=>$rowfield['field_label_cn'],
 	        "field_label_en"=>$rowfield['field_label_en'],  
 	        "field_option_cn"=>$rowfield['field_option_cn'],     
	        "field_option_en"=>$rowfield['field_option_en'],
	        "is_required"=>$field_value[$r]['isrequired'],
	        "prompt"=>$field_value[$r]['prompt'],
	        "notice"=>$field_value[$r]['notice'],
	        
	            
	    );
	    array_push($arr,$result);
	}
	}
	
	echo json_encode($arr);
}


function checkEmail()
{
	$sql="select customer_id from zy_event_customer where emailaddress='".$_REQUEST['emailaddress']."' and event_id=".$_REQUEST['event_id']."";
		$result=mysql_query($sql);
	if(mysql_num_rows($result)==0){
		//email不存在
		echo "success";
	}else{
		
		$a=mysql_fetch_array($result);
		echo $a['customer_id'];
	}

}


function checkMobile()
{
		$sql="select customer_id from zy_event_customer where mobile='".$_REQUEST['mobile']."' and event_id=".$_REQUEST['event_id']."";
		$result=mysql_query($sql);
 		if(mysql_num_rows($result)==0){
		//mobile不存在
		echo "success";
	  }else{
		$a=mysql_fetch_array($result);
		echo $a['customer_id'];
	}
}
	
function addCustomer()
{
	$flag=true;
	$event_user_id=$_REQUEST['event_user_id'];
	$event_id=$_REQUEST['event_id'];
	$partner_id=$_REQUEST['partner_id'];
	$event_code=$_REQUEST['event_code'];
	$firstname=$_REQUEST['firstname'];
	$lastname=$_REQUEST['lastname'];
	$emailaddress=$_REQUEST['emailaddress'];
	$postcode=$_REQUEST['postcode'];
	$mobile=$_REQUEST['mobile'];
	$ip=$_REQUEST['ip'];
	$lang=$_REQUEST['lang'];
	$step=$_REQUEST['step'];
    $award_address_id=$_REQUEST['award_address'];	
	if($event_user_id==""){
		$sqluserinsert="insert into zy_event_customer(event_id,partner_id,event_code,firstname,lastname,emailaddress,postcode,mobile,ip,lang,step,award_address) value ('$event_id','$partner_id','$event_code','$firstname','$lastname','$emailaddress','$postcode','$mobile','$ip','$lang','$step','$award_address_id')";
		mysql_query($sqluserinsert);
		$event_customer_id=mysql_insert_id();
	}else{
		$selectsql="select * from zy_event_customer where customer_id=$event_user_id";
		$rs=mysql_query($selectsql);
		while($row=mysql_fetch_array($rs))
		{
			$event_id=empty($event_id)?$row['event_id']:$event_id;
			$partner_id=empty($partner_id)?$row['partner_id']:$partner_id;
			$event_code=empty($event_code)?$row['event_code']:$event_code;
			$firstname=empty($firstname)?$row['firstname']:$firstname;
			$lastname=empty($lastname)?$row['lastname']:$lastname;
			$emailaddress=empty($emailaddress)?$row['emailaddress']:$emailaddress;
			$postcode=empty($postcode)?$row['postcode']:$postcode;
			$mobile=empty($mobile)?$row['mobile']:$mobile;
			$ip=empty($ip)?$row['ip']:$ip;
			$lang=empty($lang)?$row['lang']:$lang;
			$step=empty($step)?$row['step']:$step;
			$award_address_id=empty($award_address_id)?$row['award_address_id']:$award_address_id;
		}
		$sqlupdateuser="update zy_event_customer set event_id='$event_id',partner_id='$partner_id',event_code='$event_code',firstname='$firstname',lastname='$lastname',emailaddress='$emailaddress',postcode='$postcode',mobile='$mobile',ip='$ip',lang='$lang',step='$step',award_address='$award_address_id' where customer_id=$event_user_id";
		mysql_query($sqlupdateuser);
		$event_customer_id=$event_user_id;
	}
	
		$event_user_ex=$_REQUEST["event_user_extension"];
		if(strstr($event_user_ex,"\\")==true)
		{
		$str_ex=str_replace("\\","",$event_user_ex);
		}else{
		$str_ex=$event_user_ex;
		}
		$event_customer_ex=unserialize($str_ex);
     	if(count($event_customer_ex)==0)
     	{
			$flag=false;
     	}else{
			$flag=true;
     	}
		if($flag==true)
		{
		foreach ($event_customer_ex as $k => $userexval ) {
     		$sqluserexinsert="insert into zy_event_customer_extension(event_customer_id,event_customer_extension_cn,event_customer_extension_en,event_customer_extension_content) value ($event_customer_id,'','$k','$userexval')";
     		mysql_query($sqluserexinsert);
		}
	}
		$step1=$_REQUEST['step'];
		$step=$_REQUEST['step']+1;
     	
     	$sqlcount="select * from zy_event_step where event_id=".$_REQUEST['event_id'];
     	$rs=mysql_query($sqlcount);
     	$row=mysql_num_rows($rs);
     	$url="http://prepaidselect.com/demo1/surveys1.php?event_user_id=".base64_encode($event_customer_id);
     	$email_to=$_REQUEST['emailaddress'];
     	$first_name=$_REQUEST['firstname'];
     	$last_name=$_REQUEST['lastname'];
    	$mobile=$_REQUEST['mobile'];
     	$lang=$_REQUEST['lang'];
     	//邮件模板
     	$sqlemail="select email_template from zy_event_step where event_id=$event_id and step=$step1";
     	$rsemail=mysql_query($sqlemail);
     	
     	//if(mysql_num_rows($rsemail)!=0)
     	if($rsemail!=null)
     	{
     		$rowsemail=mysql_fetch_array($rsemail);
     		$sqlemailmessage="select * from zy_event_email_template where email_id=".$rowsemail['email_template'];
     		$rsemailmessage=mysql_query($sqlemailmessage);
     		$rowsemailmessage=mysql_fetch_array($rsemailmessage);
     		if($lang=="en"&&$rowsemailmessage['message_en']!=null)
     		{
     			sendEmail($email_to,$first_name,$url,$rowsemailmessage['message_en']);
     		}
    		if($lang=="cn"&&$rowsemailmessage['message_cn']!=null) 
     		{
    			sendEmail($email_to,$first_name,$url,$rowsemailmessage['message_cn']);
     		}
    	}
     	//短信模板
     	$sqlsms="select message_template from zy_event_step where event_id=$event_id and step=$step1";
     	$rssms=mysql_query($sqlsms); 
     	if($rssms!=null)
     	{
     		$rowssms=mysql_fetch_array($rssms);
     		$sqlsmsmessage="select * from zy_event_award_sms where awardSms_id=".$rowssms['message_template'];
     		$rssmsmessage=mysql_query($sqlsmsmessage);
     		$rowssmsmessage=mysql_fetch_array($rssmsmessage);
     		if($lang=="en"&&$rowssmsmessage['message_en']!=null)
     		{
     		 $text = str_replace ( "{firstName}", $first_name, $rowssmsmessage['message_en']);
     		 $text = str_replace ( "{lastName}", $last_name, $text);
     		 $post_data= array (
			 'method' => sendMessages,
			 'username' => abc,
			 'password' => 123456,
			 'mobile' => $mobile,
			 'api_id' => 53,
			 'text' => $text
			);
			 sendSms($post_data);
     		}
    		if($lang=="cn"&&$rowssmsmessage['message_cn']!=null) 
     		{
     		 $text = str_replace ( "{firstName}", $first_name, $rowssmsmessage['message_cn']);
     		 $text = str_replace ( "{lastName}", $last_name, $text);
    		 $post_data= array (
			 'method' => sendMessages,
			 'username' => abc,
			 'password' => 123456,
			 'mobile' => $mobile,
			 'api_id' => 53,
			 'text' => $text
			);
			sendSms($post_data);
     		}
    	}
     
     		$arr=array('event_user_id'=>$event_customer_id,'step'=>$step,'allstep'=>$row,'SS'=>'CNJDS');
			echo json_encode($arr);
	
	}
	
	//发送邮件
	function sendEmail($email_to,$first_name,$url,$message){
		$email_message = str_replace ( "{firstName}", $first_name, $message);
		//$email_message = str_replace ( "{lastName}",$last_name, $email_message );

			$email_message=str_replace ( "{url}", $url, $email_message);
			$email_subject  = "Netcube - 请确认注册领取您的1GB免费无线上网流量。";
			$headers = 'Content-type: text/html; charset=utf-8' . "\r\n";
			$headers .= 'From: Netcube<sales@netcube.com.au>' . "\r\n";
			$headers .= "Reply-To: ". strip_tags('sales@netcube.com.au') . "\r\n";
			$headers .= 'X-Mailer: PHP/' . phpversion() . "\r\n";
			$i=@mail($email_to, $email_subject, $email_message, $headers); 
	}
	
		//发送短信
	function sendSms($post_data)
	{
		$url = "http://sms.webnova.com.au/api/webnova_sms_api_lib.php";
				
				$ch = curl_init();
				
				curl_setopt($ch,CURLOPT_URL,$url );  
				
				curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
				   
				curl_setopt($ch,CURLOPT_FOLLOWLOCATION,0); 
				
				curl_setopt($ch, CURLOPT_POST, 1);
				
				// 把post的变量加上
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
				
				$output = curl_exec($ch);
				
				//调试使用
				if ($output === FALSE) {
					
				    $output="cURL Error: " . curl_error($ch);
				    
				}
				curl_close($ch);
	}



